package com.android.myfilm.activities;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import twitter4j.TwitterException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.external.api.RottenTomatoesUtils;
import com.android.external.apirottentomatoes.model.Movie;
import com.android.myfilm.R;
import com.android.myfilm.share.ShareOnFacebook;
import com.android.myfilm.share.twitter.AuthActivity;
import com.android.myfilm.tools.Utils;

public class MovieForm extends Activity {
	
	private ShareOnFacebook shareOnFacebook = new ShareOnFacebook(this);
	private String posterUrl;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.movie_layout_result);
		Movie movie = (Movie)this.getIntent().getExtras().getSerializable("movie");
		
		String title = movie.getTitle();
		String year = Integer.toString(movie.getYear());
		String synopsis = movie.getSynopsis();
		String poster = RottenTomatoesUtils.getPoster(movie, "profile");
		String actors = RottenTomatoesUtils.getActors(movie, 10);
		String critics_consensus = movie.getCriticsConsensus();
		this.posterUrl = poster;
		String[] directors = this.getIntent().getExtras().getStringArray("directors"); 
		
		//writing movie title
		TextView viewTitle = (TextView) findViewById(R.id.resultMovieTitle);
		viewTitle.setText(title);
		
		//writing movie year
		TextView viewYear = (TextView) findViewById(R.id.resultMovieYear);
		if (year == null || year.length() == 0)
			viewYear.setText("");
		else	
			viewYear.setText("(" + year + ")");
		
		//writing movie directors
		TextView viewDirectors = (TextView) findViewById(R.id.resultMovieDirectors);
		if (directors.length == 0) {
			viewDirectors.setText("Directors not available.");
		}
		else {
			StringBuffer directorsS = new StringBuffer();
			for (String director : directors) {
				directorsS.append(director);
				directorsS.append(", ");
			}
			int lastComma = directorsS.lastIndexOf(",");
			viewDirectors.setText((lastComma != -1?directorsS.deleteCharAt(lastComma).toString():directorsS.toString()));
		}
		
		//writing movie cast
		TextView viewCast = (TextView) findViewById(R.id.resultMovieCast);
		if (actors == null || actors.equals(""))
			viewCast.setText("No cast available.");
		else	
			viewCast.setText(actors);
		
		//writing movie synopsys
		TextView viewSynopsis = (TextView) findViewById(R.id.resultMovieSynopsis);
		if (synopsis == null || synopsis.equals(""))
			viewSynopsis.setText("No synopsis available.");
		else 
			viewSynopsis.setText(synopsis);
		
		//rendering movie poster
        ImageView imgPoster =(ImageView)findViewById(R.id.resultMoviePoster);
        
        try {
			imgPoster.setImageBitmap(BitmapFactory.decodeStream(new URL(poster).openStream()));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        //rendering rt icon and score
        int rating = movie.getRating("critics_score");
        if (rating != -1) {
        	ImageView imgRtIcon = (ImageView)findViewById(R.id.rtIcon);
        	
        	((TextView)findViewById(R.id.rtScore)).setText(rating + "%");
        	
        	if (rating >= 50) 
        		imgRtIcon.setImageResource(R.drawable.rt_fresh);
        	else
        		imgRtIcon.setImageResource(R.drawable.rt_rotten);
        }
        
        //rendering movie critics consensus
        if (critics_consensus != null && critics_consensus.length() > 0) {
	        TextView viewCriticsConsensus = (TextView)findViewById(R.id.criticsConsensus);
	        viewCriticsConsensus.setText("     \"" + critics_consensus + "\"");
        }
	}
	
	@Override
	protected void onResume() {
		super.onRestart();
		
		checkNetwork();
	}
	
	private void checkNetwork() {
		if (!Utils.isOnline(this)) {
			Utils.showToast("Network unavailable", this);
			finish();
		}
	}
	
	public boolean onKeyUp(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
	    	finish();
	    }
	    return true;
	}
	
	public void shareOnFacebook(View button) {
		Bundle params = new Bundle();
		params.putString("title", ((TextView)findViewById(R.id.resultMovieTitle)).getText().toString());
		params.putString("poster", this.posterUrl);
		
		shareOnFacebook.share(params);
	}
	
	public void shareOnTwitter(View button) throws TwitterException {
		Intent mIntent = new Intent(this, AuthActivity.class);
		mIntent.putExtra("trigger", "true");
		mIntent.putExtra("title", ((TextView)findViewById(R.id.resultMovieTitle)).getText().toString());
		startActivity(mIntent);
	}
}
